package com.tfleo.mealssenger.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.tfleo.mealssenger.LoginActivity;
import com.tfleo.mealssenger.Main;
import com.tfleo.mealssenger.utility.SecurityTools;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class UpdateLocationService extends Service {
	
	@Override
	public void onCreate() {

		// TODO Auto-generated method stub
		//Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		//Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		//Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		SharedPreferences sharedPref = getSharedPreferences(Main.APP_DATA, MODE_PRIVATE);
		if(sharedPref.getBoolean(Main.UPDATE_LOCATION, false)) {
			UpdateLocationTask task = new UpdateLocationTask();
			task.execute();
			
			super.onStartCommand(intent, flags, startId);
		}
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
		return super.onUnbind(intent);
	}

	private boolean updateLocation() {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Main.SERVER_URL + "user/updatelocation");

		float lat, lon;
		SharedPreferences sharedPref = getSharedPreferences(Main.USER_DATA, MODE_PRIVATE);
		SharedPreferences.Editor prefEditor = sharedPref.edit();

		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		String provider = LocationManager.GPS_PROVIDER;
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			provider = LocationManager.NETWORK_PROVIDER;
			//Toast.makeText(getApplicationContext(), "Switching provider", Toast.LENGTH_SHORT).show();
		}
		Location location = locationManager.getLastKnownLocation(provider);
		if(location == null) {
			lat = sharedPref.getFloat(Main.LAST_LATITUDE, 0);
			lon = sharedPref.getFloat(Main.LAST_LONGITUDE, 0);
		} else {
			lat = (float) location.getLatitude();
			lon = (float) location.getLongitude();

			prefEditor.putFloat(Main.LAST_LATITUDE, lat);
			prefEditor.putFloat(Main.LAST_LONGITUDE, lon);
			prefEditor.commit();
		}
		
		Log.i("aaa", Float.toString(lat) + " " + Float.toString(lon));
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(sharedPref.getInt(Main.USER_ID, 0))));
			nameValuePairs.add(new BasicNameValuePair("email", sharedPref.getString(Main.EMAIL, "")));
			nameValuePairs.add(new BasicNameValuePair("password", SecurityTools.decrypt(SecurityTools.MASTER_KEY, 
					sharedPref.getString(Main.TOKEN, ""))));
			nameValuePairs.add(new BasicNameValuePair("last_lat", Float.toString(lat)));
			nameValuePairs.add(new BasicNameValuePair("last_lon", Float.toString(lon)));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpclient.execute(httppost, responseHandler);
			JSONObject response = new JSONObject(responseBody);
			if(response.getInt("code") == 1) {
				return true;
			} else {
				return false;
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return false;

	}
	
	private class UpdateLocationTask extends AsyncTask<Void , Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... v) {
			return updateLocation();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				Log.i("aaa", "updated");
			} else {
				Log.e("aaa", "error can't update");
			}
		}

	}

	/*private void showNotification(String text) {
		NotificationManager	notifMan;
		notifMan = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		Notification n = new Notification();

		n.flags |= Notification.FLAG_SHOW_LIGHTS;
		n.flags |= Notification.FLAG_AUTO_CANCEL;

		n.defaults = Notification.DEFAULT_ALL;

		n.icon = R.drawable.icon;
		n.when = System.currentTimeMillis();

		// Simply open the parent activity
		//TODO
		Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0,
				i, 0);

		// Change the name of the notification here
		n.setLatestEventInfo(this, "Reminder", text, pi);

		notifMan.notify(0, n);
	}*/
}